/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.quickorm.core.support;

import com.quickorm.core.QuickormTemplate;
import com.quickorm.core.impl.QuickormTemplateImpl;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

/**
 *
 * @author aaa
 */
public abstract class QuickormDaoSupport {

    private QuickormTemplate quickormTemplate;

    /**
     * Set the JDBC DataSource to be used by this DAO.
     */
    public final void setDataSource(DataSource dataSource) {
        if (this.quickormTemplate == null || dataSource != this.quickormTemplate.getDataSource()) {
            setQuickormTemplate(createQuickormTemplate(dataSource));
        }
    }

    protected QuickormTemplate createQuickormTemplate(DataSource dataSource) {
        return new QuickormTemplateImpl(dataSource);
    }

    public final DataSource getDataSource() {
        return (quickormTemplate != null ? quickormTemplate.getDataSource() : null);
    }

    public void setQuickormTemplate(QuickormTemplate quickormTemplate) {
        this.quickormTemplate = quickormTemplate;
        initTemplateConfig();
    }

    public QuickormTemplate getQuickormTemplate() {
        return this.quickormTemplate;
    }

    /**
     * Initialize the template-based configuration of this DAO. Called after a
     * new JdbcTemplate has been set, either directly or through a DataSource.
     * <p>This implementation is empty. Subclasses may override this to
     * configure further objects based on the JdbcTemplate.
     *
     * @see #getJdbcTemplate()
     */
    protected void initTemplateConfig() {
    }

    protected void checkDaoConfig() {
        if (getQuickormTemplate() == null) {
            throw new IllegalArgumentException("'dataSource' or 'quickormTemplate' is required");
        }
    }

    protected final Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }
}
